package com.tencreat.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencreat.common.config.TencentConfig;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.redis.RedisCache;
import com.tencreat.common.enums.account.CitySmsTypeEnum;
import com.tencreat.common.enums.account.TencreatTips;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.domain.account.AccountLoginCheck;
import com.tencreat.domain.account.dto.ShopOpenSendCodeDTO;
import com.tencreat.service.account.IAccountLoginCheckService;
import com.tencreat.service.system.ISysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/***
 * 腾讯云短信实现
 */
@Slf4j
@Service
@Configuration
@ConditionalOnProperty(prefix = "sys.message", name = "impl", havingValue = "tencent")
public class SysTencentMessageServiceImpl implements ISysMessageService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IAccountLoginCheckService accountLoginCheckService;



    /*****
     * 发送验证码接口
     * @param openSendCodePO
     * @return
     */
    @Override
    public void sendSMS(ShopOpenSendCodeDTO openSendCodePO) {
        throw new CustomException("暂不支持");
//        TencentConfig tencentConfig = TencentConfig.getAliConfig();
//        // 对需要判断用户是否已经注册的用户类型进行统一处理
//        if (CitySmsTypeEnum.FORGET_PASSWORD.getType().equals(openSendCodePO.getType())) {
//            AccountLoginCheck dbAccountInfo = accountLoginCheckService.getOne(new QueryWrapper<AccountLoginCheck>().eq("phone", openSendCodePO.getPhone()));
//            if (null == dbAccountInfo) {
//                return HttpResult.error(TencreatTips.Code.PHONE_NOT_REGISTERED);
//            }
//            if ("2".equals(dbAccountInfo.getDelFlag())) {
//                return HttpResult.error(TencreatTips.Account.ACCOUNT_NOT_EXIST);
//            }
//        }
//
//        // 缓存验证码
//        String cacheKey = "";
//        String code = TenCreatUtil.getRandomNumCode(4);
//        if (openSendCodePO.getType().equals(CitySmsTypeEnum.CHECK_OLD_PHONE.getType())){
//            cacheKey= openSendCodePO.getPhone()+"CHECK_OLD_PHONE";
//        }else if (openSendCodePO.getType().equals(CitySmsTypeEnum.CHECK_NEW_PHONE.getType())){
//            cacheKey= openSendCodePO.getPhone()+"CHECK_NEW_PHONE";
//        }else if (openSendCodePO.getType().equals(CitySmsTypeEnum.REGISTERED.getType())){
//            cacheKey= openSendCodePO.getPhone()+"REGISTERED";
//        }else {
//            cacheKey= openSendCodePO.getPhone();
//        }
//
//        if(redisCache.hasKey(cacheKey)){
//            return HttpResult.error(TencreatTips.Code.CODE_HAS);
//        }
//
//        String[] phoneNumberSet = {"+86"+openSendCodePO.getPhone()};
//        String[] paramSet = {code,tencentConfig.getCodeValidTime()};
//
//        //发送信息
//        SendSmsResponse result = sms(tencentConfig.getCodeTemplate(),phoneNumberSet,paramSet);
//        if("Ok".equals(result.getSendStatusSet()[0].getCode())){
//            redisCache.setCacheObject(cacheKey, code,60, TimeUnit.SECONDS);
//            return HttpResult.ok(result.getSendStatusSet()[0].getMessage());
//        }
//        return HttpResult.error(result.getSendStatusSet()[0].getMessage());
    }

    @Override
    public void verifySmsCode(CitySmsTypeEnum type, String phone, String code) {
        throw new CustomException("暂不支持");
    }

    @Override
    public void auditMallSupplier(String phone, String conent) {
        TencentConfig tencentConfig = TencentConfig.getAliConfig();
        String[] phoneNumberSet = {"+86"+phone};
        String[] paramSet = {};
        sms(tencentConfig.getSupplierTemplate(),phoneNumberSet,paramSet);
    }

    @Override
    public void auditMallStore(String phone, String conent) {
        TencentConfig tencentConfig = TencentConfig.getAliConfig();
        String[] phoneNumberSet = {"+86"+phone};
        String[] paramSet = {};
        sms(tencentConfig.getStoreTemplate(),phoneNumberSet,paramSet);
    }

    @Override
    public void smsSupplierApproved(String phone, String userName,String password) {
        TencentConfig tencentConfig = TencentConfig.getAliConfig();
        String[] phoneNumberSet = {"+86"+phone};
        String[] paramSet = {userName,password};
        sms(tencentConfig.getSupplierApprovedTemplate(),phoneNumberSet,paramSet);
    }


    @Override
    public void smsStoreApproved(String phone, String userName, String password) {
        TencentConfig tencentConfig = TencentConfig.getAliConfig();
        String[] phoneNumberSet = {"+86"+phone};
        String[] paramSet = {userName,password};
        sms(tencentConfig.getStoreApprovedTemplate(),phoneNumberSet,paramSet);
    }

    @Override
    public void pushMessage(String phone, String conent) {
        TencentConfig tencentConfig = TencentConfig.getAliConfig();
        String[] phoneNumberSet = {"+86"+phone};
        String[] paramSet = {};
        sms(tencentConfig.getPushMessageTemplate(),phoneNumberSet,paramSet);
    }

    /******
     *
     * @param templateId 模板ID
     * @param paramSet 模板参数 {"5678"}
     * @param phoneNumberSet  下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
     *                         示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号
     * @return
     */
    private SendSmsResponse sms(String templateId, String[] phoneNumberSet,String[] paramSet) {
        TencentConfig tencentConfig = TencentConfig.getAliConfig();
        try {
            //后期可以更改为环境变量获取
            Credential cred = new Credential(tencentConfig.getSecretId(), tencentConfig.getSecretKey());
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
            SendSmsRequest req = new SendSmsRequest();

            req.setSmsSdkAppId(tencentConfig.getSdkAppId());
            req.setSignName(tencentConfig.getSignName());
            req.setTemplateId(templateId);
            req.setPhoneNumberSet(phoneNumberSet);
            req.setTemplateParamSet(paramSet);

            SendSmsResponse res = client.SendSms(req);
            log.info(SendSmsResponse.toJsonString(res));
            return res;
        } catch (TencentCloudSDKException e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
